<template>
    <div class="disease-management"
        style="padding: 20px; background: #f5f7fa; min-height: 100vh; width: 100%; display: flex; gap: 20px;">

        <!-- 左侧导航 -->
        <div class="category-nav"
            style="width: 200px; background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <span style="font-size: 14px; color: #666;">病种列表</span>
                <el-button type="primary" size="small" @click="handleAddDisease">+ 病种</el-button>
            </div>

            <el-menu :default-active="activeDisease" @select="handleDiseaseChange" style="border-right: none;">
                <el-menu-item v-for="item in categories" :key="item.listofdiseasesId"
                    :index="item.listofdiseasesId.toString()">
                    {{ item.listofdiseasesName }}
                </el-menu-item>
            </el-menu>
        </div>

        <!-- 右侧主内容区 -->
        <div class="main-content"
            style="flex: 1; background: white; border-radius: 8px; padding: 30px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">

            <!-- 操作按钮 -->
            <div style="margin-bottom: 20px;">
                <el-button type="primary" size="small" @click="handleAddGroup">+ 新增</el-button>
            </div>

            <!-- 表格 -->
            <el-table :data="tableData" stripe border style="width: 100%;"
                :header-cell-style="{ background: '#f8f9fa', color: '#333', fontSize: '14px' }"
                :cell-style="{ padding: '8px 12px', fontSize: '14px' }" row-key="id">
                <el-table-column prop="codeName" label="组名称" min-width="120" />
                <el-table-column prop="codeNum" label="组编码" min-width="120" />
                <el-table-column prop="colormarking" label="颜色标签" width="100">
                    <template #default="{ row }">
                        <div
                            :style="{ width: '30px', height: '20px', backgroundColor: row.colormarking, borderRadius: '4px' }">
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                    :page-sizes="[2, 5, 10, 15]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                    :total="page.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

        </div>

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑组' : '新增组'" width="500px" destroy-on-close>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
                <el-form-item label="组名称:" prop="codeName">
                    <el-input v-model="formData.codeName" placeholder="请输入组名称" clearable />
                </el-form-item>
                <el-form-item label="组编码:" prop="codeNum">
                    <el-input v-model="formData.codeNum" placeholder="请输入组编码" clearable />
                </el-form-item>
                <el-form-item label="颜色标识:" prop="colormarking">
                    <el-color-picker v-model="formData.colormarking" show-alpha />
                </el-form-item>
                <el-form-item label="病种类型" prop="listofdiseasesId">
                    <el-select v-model="formData.listofdiseasesId" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in categories" :key="item.listofdiseasesId"
                            :label="item.listofdiseasesName" :value="item.listofdiseasesId" />
                    </el-select>

                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 新增病种弹窗 -->
        <el-dialog v-model="addDiseaseVisible" title="新增病种" width="500px" destroy-on-close>
            <el-form ref="addDiseaseFormRef" :model="addDiseaseFormData" :rules="addDiseaseRules" label-width="100px">
                <el-form-item label="病种名称:" prop="listofdiseasesName">
                    <el-input v-model="addDiseaseFormData.listofdiseasesName" placeholder="请输入病种名称" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDiseaseVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddDiseaseSubmit">保存</el-button>
                </span>
            </template>
        </el-dialog>



    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
const categories = ref([])
// 新增病种弹窗相关
const addDiseaseVisible = ref(false)
const addDiseaseFormRef = ref(null)


// 表格数据
const tableData = ref([])

// 分页参数（新增 ListofdiseasesId ）
const page = reactive({
    pageIndex: 1,
    pageSize: 5,
    totalPage: 1,
    totalCount: 0,
    listofdiseasesId: null // 👈 用于病种过滤
})

// 获取数据
const list = () => {
    axios.get('http://localhost:5108/api/Manager/DiseasemanagShow', { params: page })
        .then(res => {
            tableData.value = res.data.data.data
            page.totalCount = res.data.data.totalCount;
            page.totalPage = res.data.data.totalPage;
            console.log(res.data.data.data)
        })
}


// 分页变化
const handleSizeChange = (pageSize) => {
    page.pageSize = pageSize
    list();
}

const handleCurrentChange = (pageIndex) => {
    page.pageIndex = pageIndex
    list();
}
// 当前选中的病种
const activeDisease = ref('1')

// 弹窗相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref(null)

// 表单数据
const formData = reactive({
    id: null,
    listofdiseasesId: null,
    codeName: '',
    codeNum: '',
    colormarking: ''
})



// 新增组
const handleAddGroup = () => {
    isEditing.value = false
    formData.listofdiseasesId = parseInt(activeDisease.value) // 👈 默认当前病种
    formData.codeName = ''
    formData.codeNum = ''
    formData.colormarking = '#409EFF'
    dialogVisible.value = true
}

// 编辑组
const handleEdit = (row) => {
    isEditing.value = true
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 保存表单
const handleSubmit = async () => {
    try {
        await formRef.value.validate()

        const url = isEditing.value
            ? `http://localhost:5203/api/Managment/PutDisease`
            : 'http://localhost:5203/api/Managment/AddDisease'

        const method = isEditing.value ? 'put' : 'post'

        const payload = {
            ...formData,
            listofdiseasesId: formData.listofdiseasesId || parseInt(activeDisease.value)
        }

        await axios[method](url, payload)

        ElMessage.success('保存成功')
        dialogVisible.value = false
        list()
    } catch (err) {
        console.error(err)
        ElMessage.error('保存失败')
    }
}

// 删除组
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除 "${row.codeName}"？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(() => {
        axios.delete(`http://localhost:5108/api/Manager/DiseasemanagDelete/${row.id}`)
            .then(() => {
                ElMessage.success('删除成功')
                list()
            })
    })
}


// 初始化
onMounted(() => {
    list();
    listCategory();
})


// 新增病种表单数据
const addDiseaseFormData = reactive({
    listofdiseasesName: ''
})

// 新增病种表单验证规则
const addDiseaseRules = {
    listofdiseasesName: [{ required: true, message: '请输入病种名称', trigger: 'blur' }]
}

// 新增病种
const handleAddDisease = () => {
    addDiseaseVisible.value = true
    addDiseaseFormData.listofdiseasesName = '' // 清空表单
}
// 保存新增病种
const handleAddDiseaseSubmit = async () => {
    try {
        await addDiseaseFormRef.value.validate()

        const url = 'http://localhost:5203/api/Managment/AddListofdiseases'
        const method = 'post'

        const payload = {
            listofdiseasesName: addDiseaseFormData.listofdiseasesName
        }

        await axios[method](url, payload)

        ElMessage.success('新增病种成功')
        addDiseaseVisible.value = false
        listCategory() // 👈 关键：刷新分类列表
        // 可选：自动选中新增的病种
        // activeDisease.value = 新增病种的 ID（如果后端返回）
    } catch (err) {
        console.error(err)
        ElMessage.error('新增病种失败')
    }
}

// 获取分类
const listCategory = () => {
    axios.get('http://localhost:5108/api/Manager/ListofdiseasesSelect')
        .then(res => {
            categories.value = res.data.data
            // 如果当前选中的病种不在新列表中，重置为第一个
            if (!categories.value.some(item => item.listofdiseasesId == activeDisease.value)) {
                activeDisease.value = categories.value[0]?.listofdiseasesId || '1'
            }
        })
}



// 切换病种
const handleDiseaseChange = (index) => {
  activeDisease.value = index
  page.listofdiseasesId = parseInt(index)
  page.pageIndex = 1
  list()
}


</script>

<style scoped>
/* 颜色标识样式 */
.el-color-picker {
    width: 100%;
}
</style>